package cc.mrbird.febs.common.service;

import cc.mrbird.febs.common.baidu.AuthService;
import cc.mrbird.febs.common.baidu.util.Base64Util;
import cc.mrbird.febs.common.baidu.util.FileUtil;
import cc.mrbird.febs.common.baidu.util.GsonUtils;
import cc.mrbird.febs.common.baidu.util.HttpUtil;
import cc.mrbird.febs.common.controller.BaseController;
import cc.mrbird.febs.system.entity.User;
import cc.mrbird.febs.system.service.IUserService;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class FaceService extends BaseController {

    @Resource
    private IUserService userService;

    public void faceMatch(String filePath) {
        User currentUser = getCurrentUser();
        try {
           /* byte[] bytes1 = FileUtil.readFileByBytes(filePath);
            byte[] bytes2 = FileUtil.readFileByBytes(currentUser.getFaceUrl());
            String image1 = Base64Util.encode(bytes1);
            String image2 = Base64Util.encode(bytes2);*/

            String image1 = FileUtil.getImageBase64(filePath);
            String image2 = FileUtil.getImageBase64(currentUser.getFaceUrl());

            List<Map<String, Object>> images = new ArrayList<Map<String, Object>>();
            // 请求url
            String url = "https://aip.baidubce.com/rest/2.0/face/v3/match";
            Map<String, Object> map1 = new HashMap<String, Object>(16);
            map1.put("image", image1);
            map1.put("image_type", "BASE64");
            map1.put("face_type", "LIVE");
            map1.put("quality_control", "LOW");
            map1.put("liveness_control", "NORMAL");

            Map<String, Object> map2 = new HashMap<String, Object>();
            map2.put("image", image2);
            map2.put("image_type", "BASE64");
            map2.put("face_type", "LIVE");
            map2.put("quality_control", "LOW");
            map2.put("liveness_control", "NORMAL");

            images.add(map1);
            images.add(map2);

            String param = GsonUtils.toJson(images);

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
//            String accessToken = "[调用鉴权接口获取的token]";
            String accessToken = AuthService.getAuth();

            String result = HttpUtil.post(url, accessToken, "application/json", param);
            JSONObject jsonObject = new JSONObject(result);
            System.out.println("jsonObject---->>>-- " + jsonObject);
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
